package com.mohansever.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.mohansever.dao.ArticleDao;
import com.mohansever.dao.ContentDao;
import com.mohansever.pojo.Article;
import com.mohansever.pojo.Content;
import com.mohansever.rep.ArticleMRep;
import com.mohansever.rep.ArticlePageRep;
import com.mohansever.rep.ContentMRep;
import com.mohansever.rep.UserPageRep;
import com.mohansever.req.AddArticleMReq;
import com.mohansever.req.ContentMReq;
import com.mohansever.service.ArticleMService;
import com.mohansever.tool.Base64CC;
import com.mohansever.util.ArticlePageQuery;
import com.mohansever.util.ErrStatusEnum;
import com.mohansever.util.PageData;
import com.mohansever.util.PageQUery;
import com.mohansever.util.ResponseUtil;
import com.mohansever.util.UserMap;

@Service("articleMService")
public class ArticleMServiceImpl implements ArticleMService{
	@Resource 
	private ArticleDao articleDao;
	@Resource 
	private ContentDao contentDao;
	
	/**
	 * 后台添加文章
	 */
	@Override
	public ResponseUtil addArticleM(AddArticleMReq aaMReq){
		ResponseUtil rep = new ResponseUtil();		
		try {
			/**
			 * 1.插入article表
			 */
			Article article = articleM2Article(aaMReq);
			article.setLoves(0);
			article.setReview(3);
			article.setRecommend(1);
			this.articleDao.insertArticle(article);
			Integer aId = this.articleDao.selectaLastArticleId();
			if (aId == null) {
				rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
			} else {
				int articleId = aId.intValue();
				/**
				 * 2.插入文段
				 */
				List<Content> contents = cM2C(aaMReq.getArticle().getContents(),articleId);
				for (Content content : contents) {
					this.contentDao.insertContent(content);
				}
				
				/**
				 * 3.更新article表里contentIds
				 */
				updateContentIds(articleId);
				rep.defaultSuccess("新增文章成功");
			}
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			rep.fail(ErrStatusEnum.PARMERR.getCode(), ErrStatusEnum.PARMERR.getMessage());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
		}
		
		return rep;
	}
	
	/**
	 * 后台删除文章(真删除)
	 */
	@Override
	public ResponseUtil delArticleM(PageData pd) throws Exception{
		ResponseUtil rep = new ResponseUtil();
		try {
			/**
			 * 1.删除content
			 */
			this.contentDao.deleteContents(pd.getInt("articleId"));
			/**
			 * 2.删除article
			 */
			this.articleDao.deleteArticle(pd.getInt("articleId"));
			rep.defaultSuccess("文章删除成功");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
		}
		return rep;
	}
	
	/**
	 * 后台更新文章
	 */
	@Override
	public ResponseUtil updateArticleM(AddArticleMReq aaMReq) throws Exception{
		ResponseUtil rep = new ResponseUtil();
		try {
			/**
			 * 1.修改article
			 */
			if (aaMReq.getArticle().getArticleId() < 1) {
				rep.fail(ErrStatusEnum.PARMERR.getCode(), ErrStatusEnum.PARMERR.getMessage());
			} else {
				Article article = articleM2Article(aaMReq);
				article.setArticleId(aaMReq.getArticle().getArticleId());
				this.articleDao.updateArticle(article);
				/**
				 * 2.删除旧的content
				 */
				this.contentDao.deleteContents(article.getArticleId());
				/**
				 * 3.插入新的content
				 */
				List<Content> contents = cM2C(aaMReq.getArticle().getContents(),article.getArticleId());
				for (Content content : contents) {
					this.contentDao.insertContent(content);
				}
				/**
				 * 4.更新article表里contentIds
				 */
				updateContentIds(article.getArticleId());
				rep.defaultSuccess("文章修改成功");
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
		}
		
		return rep;
	}
	
	/**
	 * 分页获取用户文章列表
	 */
	@Override
	public ResponseUtil getPageList(PageData pd) throws Exception{
		ResponseUtil rep = new ResponseUtil();
		try {
			rep = getArticleList(pd);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
		}
		return rep;
	}
	
	/**
	 * 根据articleId获取文章内容
	 */
	@Override
	public ResponseUtil getArticle(PageData pd) throws Exception{
		ResponseUtil rep = new ResponseUtil();
		try {
			/**
			 * 1.获取article
			 */
			PageData pdArticle = this.articleDao.getArticle(pd.getInt("articleId"));
			if (pdArticle == null) {
				rep.fail(ErrStatusEnum.NOTARGET.getCode(), ErrStatusEnum.NOTARGET.getMessage());
			}else {
				ArticleMRep aMRep = article2aMRep(pdArticle);
				rep.defaultSuccess(aMRep);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
		}
		return rep;
	}
	
	/**
	 * 修改文章的状态
	 */
	@Override
	public ResponseUtil chgArticleStatus(PageData pd) throws Exception{
		ResponseUtil rep = new ResponseUtil();
		try {
			if (pd.getInt("articleStatus")>0 && pd.getInt("articleStatus")<5) {
				this.articleDao.updateArticleStatus(pd);
				rep.defaultSuccess("修改文章状态成功");
			}else {
				rep.fail(ErrStatusEnum.PARMERR.getCode(), ErrStatusEnum.PARMERR.getMessage());
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
		}
		return rep;
	}
	
	/**
	 * 修改文件推荐
	 */
	@Override
	public ResponseUtil chgArticleRecommend(PageData pd) throws Exception{
		ResponseUtil rep = new ResponseUtil();
		try {
			if (pd.getInt("recommend")>0 && pd.getInt("recommend")<3) {
				this.articleDao.updateArticleRecommend(pd);
				rep.defaultSuccess("修改文章推荐状态成功");
			}else {
				rep.fail(ErrStatusEnum.PARMERR.getCode(), ErrStatusEnum.PARMERR.getMessage());
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
		}
		return rep;
	}
	
	/**
	 * 修改文章公开状态
	 */
	@Override
	public ResponseUtil chgArticleIsOpen(PageData pd) throws Exception{
		ResponseUtil rep = new ResponseUtil();
		try {
			if (pd.getInt("isOpen")>0 && pd.getInt("isOpen")<3) {
				this.articleDao.updateArticleIsOpen(pd);
				rep.defaultSuccess("修改文章公开状态成功");
			}else {
				rep.fail(ErrStatusEnum.PARMERR.getCode(), ErrStatusEnum.PARMERR.getMessage());
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
		}
		return rep;
	}
	
	/**
	 * 修改文章类别
	 */
	@Override
	public ResponseUtil chgArticleClass(PageData pd) throws Exception{
		ResponseUtil rep = new ResponseUtil();
		try {
			if (pd.getInt("articleClass")>0 && pd.getInt("articleClass")<3) {
				this.articleDao.updateArticleClass(pd);
				rep.defaultSuccess("修改文章类别成功");
			}else {
				rep.fail(ErrStatusEnum.PARMERR.getCode(), ErrStatusEnum.PARMERR.getMessage());
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			rep.fail(ErrStatusEnum.SYSERR.getCode(), ErrStatusEnum.SYSERR.getMessage());
		}
		return rep;
	}
	
	/**
	 * articleM 转成article
	 * @param aaMReq
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private Article articleM2Article(AddArticleMReq aaMReq) throws UnsupportedEncodingException{
		Article article = new Article();
		article.setAnalysis(Base64CC.decode(aaMReq.getArticle().getAnalysis()));
		article.setArticleClass(aaMReq.getArticle().getArticleStatus());
		article.setArticleProfile(Base64CC.decode(aaMReq.getArticle().getArticleProfile()));
		article.setArticleStatus(aaMReq.getArticle().getArticleStatus());
		article.setAuthor(Base64CC.decode(aaMReq.getArticle().getAuthor()));
		article.setBook(Base64CC.decode(aaMReq.getArticle().getBook()));
		article.setCountry(Base64CC.decode(aaMReq.getArticle().getCountry()));
		article.setCreateTime(aaMReq.getArticle().getCreateTime());
		article.setDynasty(Base64CC.decode(aaMReq.getArticle().getDynasty()));
		article.setIsOpen(aaMReq.getArticle().getIsOpen());
		article.setStyle(Base64CC.decode(aaMReq.getArticle().getStyle()));
		article.setTags(Base64CC.decode(aaMReq.getArticle().getTags()));
		article.setTitle(Base64CC.decode(aaMReq.getArticle().getTitle()));
		article.setType(aaMReq.getArticle().getType());
		article.setUserId(aaMReq.getArticle().getUserId());
		return article;
	}
	
	/**
	 * contentM装成content
	 * @param cms
	 * @param aId
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private List<Content> cM2C(List<ContentMReq> cms,int aId) throws UnsupportedEncodingException{
		List<Content> cs = new ArrayList<Content>();
		if (!cms.isEmpty()) {
			for (ContentMReq cm : cms) {
				Content c = new Content();
				c.setArticleId(aId);
				c.setContent(Base64CC.decode(cm.getContent()));
				c.setFontColor(cm.getFontColor());
				c.setFontSize(cm.getFontSize());
				c.setSerialNum(cm.getSerialNum());
				cs.add(c);
			}
		}
		return cs;
	}
	
	/**
	 * 修改article的contentIds
	 * @param articleId
	 * @throws Exception
	 */
	public void updateContentIds(int articleId) throws Exception{
		/**
		 * 1.获取值是articleId的所有contentId
		 */
		List<Integer> cIds = this.contentDao.selectContentIdsByArticleId(articleId);
		String cIdStr = "[";
		if (cIds.isEmpty()) {
			cIdStr = cIdStr + "]";
		}else {
			for (Integer integer : cIds) {
				cIdStr = cIdStr + integer.toString() + ",";
			}
			cIdStr = cIdStr.substring(0, cIdStr.length() - 1);
			cIdStr = cIdStr + "]";
		}
		
		/**
		 * 2.更新article的contentIds
		 */
		Article article = new Article();
		article.setArticleId(articleId);
		article.setContentIds(cIdStr);
		this.articleDao.updteContentIds(article);
		
	}
	
	/**
	 * 分页获取文章
	 * @param pd
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@SuppressWarnings("unchecked")
	private ResponseUtil getArticleList(PageData pd) throws UnsupportedEncodingException{
		ResponseUtil rep = new ResponseUtil();
		ArticlePageQuery apq = new ArticlePageQuery();
		
		Integer recordSize = this.articleDao.selectRecordSizeByUserId(pd.getString("targetUserId"));
		if (recordSize == null) {
			//数据为0
			ArticlePageRep aPageRep = new ArticlePageRep();
			aPageRep.setTotalRecord(0);
			rep.defaultSuccess(aPageRep);
		} else {
			int totalRecord = recordSize.intValue();
			//int pageSize = (int) Math.ceil(totalRecord/(pData.getInt("eachPageSize") * 1.0));
			int start = (pd.getInt("queryPage") - 1)*pd.getInt("eachPageSize");
			apq.setBegin(start);
			apq.setEach(pd.getInt("eachPageSize"));		
			apq.setUserId(pd.getString("targetUserId"));
			List<PageData> articles = this.articleDao.selectPageList(apq);	
			for (PageData pageData : articles) {
				pageData.replace("title", Base64CC.encode(pageData.getString("title")));
				pageData.replace("author", Base64CC.encode(pageData.getString("title")));
				pageData.replace("dynasty", Base64CC.encode(pageData.getString("dynasty")));
			}
			ArticlePageRep aPageRep = new ArticlePageRep();
			aPageRep.setTotalRecord(totalRecord);
			aPageRep.setArticles(articles);
			rep.defaultSuccess(aPageRep);
		}
	
		return rep;
	}

	/**
	 * 组装文章内容
	 * @param pdArticle
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private ArticleMRep article2aMRep(PageData pdArticle) throws UnsupportedEncodingException{
		ArticleMRep aMRep = new ArticleMRep();
		aMRep.setAnalysis(Base64CC.encode(pdArticle.getString("analysis")));
		aMRep.setArticleClass(pdArticle.getInt("articleClass"));
		aMRep.setArticleId(pdArticle.getInt("articleId"));
		aMRep.setArticleProfile(Base64CC.encode(pdArticle.getString("articleProfile")));
		aMRep.setArticleStatus(pdArticle.getInt("articleStatus"));
		aMRep.setAuthor(Base64CC.encode(pdArticle.getString("author")));
		aMRep.setBook(Base64CC.encode(pdArticle.getString("book")));
		aMRep.setBookId(pdArticle.getInt("bookId"));
		aMRep.setCountry(Base64CC.encode(pdArticle.getString("country")));
		aMRep.setCreateTime(pdArticle.getString("createTime"));
		aMRep.setDynasty(Base64CC.encode(pdArticle.getString("dynasty")));
		aMRep.setIsOpen(pdArticle.getInt("isOpen"));
		aMRep.setLoves(pdArticle.getInt("loves"));
		aMRep.setRecommend(pdArticle.getInt("recommend"));
		aMRep.setReview(pdArticle.getInt("review"));
		aMRep.setStyle(Base64CC.encode(pdArticle.getString("style")));
		aMRep.setTags(Base64CC.encode(pdArticle.getString("tags")));
		aMRep.setTitle(Base64CC.encode(pdArticle.getString("title")));
		aMRep.setType(pdArticle.getInt("type"));
		aMRep.setUserId(pdArticle.getString("userId"));
		
		List<ContentMRep> contents = new ArrayList<ContentMRep>();
		List<PageData> contentsPd = this.contentDao.selectContents(pdArticle.getInt("articleId"));
		for (PageData pageData : contentsPd) {
			ContentMRep cmRep = new ContentMRep();
			cmRep.setContent(Base64CC.encode(pageData.getString("content")));
			cmRep.setFontColor(pageData.getString("fontColor"));
			cmRep.setFontSize(pageData.getInt("fontSize"));
			cmRep.setSerialNum(pageData.getInt("serialNum"));
			contents.add(cmRep);
		}
		
		aMRep.setContents(contents);
		
		return aMRep;
	}
}
